package cn.chengpengper.seckill.activity.application.event.handler;

import cn.chengpengper.seckill.activity.application.cache.service.SeckillActivityCacheService;
import cn.chengpengper.seckill.activity.application.cache.service.SeckillActivityListCacheService;
import cn.chengpengper.seckill.activity.domain.event.SeckillActivityEvent;
import cn.chengpengper.seckill.common.constants.SeckillConstants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @author chengpeng.hu
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = SeckillConstants.EVENT_ACTIVITY_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_EVENT_ROCKETMQ_ACTIVITY)
public class SeckillActivityRocketMqEventHandler implements RocketMQListener<String> {

    private final SeckillActivityCacheService seckillActivityCacheService;

    private final SeckillActivityListCacheService seckillActivityListCacheService;

    @Override
    public void onMessage(String msg) {
        log.info("SeckillActivityRocketMqEventHandler|接收到活动事件|{}", msg);
        if (StringUtils.isBlank(msg)) {
            log.info("SeckillActivityRocketMqEventHandler|事件参数错误");
            return;
        }
        SeckillActivityEvent seckillActivityEvent = this.getEventMessage(msg);
        seckillActivityCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getId(), false);
        seckillActivityListCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getStatus(), false);
    }

    private SeckillActivityEvent getEventMessage(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String eventStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillActivityEvent.class);
    }
}
